<template>
  <!-- 打印电子面单组件 -->
  <div v-loading="loading" element-loading-text="加载中">
    <el-form :model="printForm" label-width="120px" label-position="right">
      <el-form-item label="对接平台类型：">
        <el-select v-model="printForm.platformType" :disabled="platformDisabled" placeholder="请选择" @change="platformTypeChange()" class="width-260">
          <el-option v-for="item in platformTypeList" :key="item.value" :label="item.label" :value="item.value">
          </el-option>
        </el-select>
      </el-form-item>

      <el-form-item label="快递公司：">
        <el-select v-model="printForm.enterpriseExpressId" placeholder="请选择" clearable @change="expressChange()" class="width-260">
          <el-option v-for="(express, index) in expressList"
            :key="index"
            :label="express.enterpriseExpressOutletsList[0].expressName"
            :value="express.enterpriseExpressOutletsList[0].enterpriseExpressId">
          </el-option>
        </el-select>
      </el-form-item>

      <el-form-item label="对接网点类型：">
        <el-select v-model="printForm.expressOutletsId" placeholder="请选择" disabled class="width-260">
          <el-option v-for="(outlets, index) in outletsList"
            :key="index"
            :label="outlets.sendName"
            :value="outlets.enterpriseExpressOutletsId">
          </el-option>
        </el-select>
      </el-form-item>

      <el-form-item label="打印机：" v-if="printForm.platformType != 999">
        <el-select v-model="printForm.printerName" :disabled="printerDisabled" placeholder="请选择" class="width-260">
          <el-option v-for="(printer, index) in printersList"
            :key="index"
            :label="printer.name"
            :value="printer.name">
          </el-option>
        </el-select>
      </el-form-item>

    </el-form>

    <!-- 底部按钮 -->
    <div slot="footer" class="dialog-footer">
      <el-button @click="doClose">取消</el-button>
      <el-button :disabled="printButton" type="primary" @click="doPrint">打印</el-button>
    </div>
  </div>
</template>

<script>
  import { getOrderInfo } from '@/api/goods/order'
  import { printProjectSend, updateProjectSendPrintStatus } from '@/api/order/projectSend'
  import { listAllExpressOutlets } from '@/api/goods/expressOutlets'
  import { getVillageSupplier } from '@/api/user/supplier'
  import { getWarehouse } from '@/api/warehouse/warehouseInfo'
  import { listWarehouseOutlets } from '@/api/warehouse/warehouseDefaultExpressOutlets'

  export default {
    props: {
      showFlag: {
        type: Boolean,
        default() {
          return false
        }
      },
      printList: {
        type: Array,
        default() {
          return []
        }
      }
    },
    watch: {
      showFlag(val) {
        if (val) {
          this.init()
        }
      }
    },
    data() {
      return {
        douYinSocket: '',
        taoBaoSocket: '',
        pinDuoDuoSocket: '',
        // 默认打印机名称
        defaultPrinter: '',
        // 打印机地址
        printerAddress: '',
        // 打印表单
        printForm: {
          sendId: '',
          orderId: '',
          enterpriseExpressId: '',
          platformType: '',
          expressOutletsId: '',
          printerName: ''
        },
        // 平台类型集合
        platformTypeList: [{
          value: 999,
          label: '快递鸟面单'
        }, {
          value: 1,
          label: '抖音面单'
        }, {
          value: 3,
          label: '淘宝面单'
        }, {
          value: 4,
          label: '拼多多面单'
        }],
        // 物流集合
        expressList: [],
        // 网点集合
        outletsList: [],
        // 打印机列表
        printersList: [],
        platformDisabled: false,
        loading: false,
        printerDisabled: true,
        // 父页面刷新flag
        refreshFlag: false,
        // 运单号
        trackNo: '',
        printButton: false,
        // 面单使用数据类型：1-企业数据；2-供应商数据
        kuaiDiNiaoUseType: '',
        taoBaoUseType: '',
        douYinUseType: '',
        pinDuoDuoUseType: ''
      }
    },
    // 初始化页面
    created() {
      // 获取供应商使用面单方式：1-企业；2-供应商
      const initFx = new Promise((resolve, reject) => {
        if (this.getWarehouseId()) {
          getWarehouse(this.getWarehouseId()).then((response) => {
            if (response.isError) return
            const warehouseSource = response.data.warehouseSource
            // 供应商仓
            if (warehouseSource === 2) {
              const supplierId = response.data.supplierId
              getVillageSupplier(supplierId).then(response => {
                if (response.isError) return
                this.kuaiDiNiaoUseType = response.data.kuaiDiNiaoUseType
                this.douYinUseType = response.data.douYinUseType
                this.taoBaoUseType = response.data.taoBaoUseType
                this.pinDuoDuoUseType = response.data.pinDuoDuoUseType
                resolve('success')
              })
            } else {
              resolve('success')
            }
          })
        } else if (this.getSupplierId()) {
          getVillageSupplier(this.getSupplierId()).then(response => {
            if (response.isError) return
            this.kuaiDiNiaoUseType = response.data.kuaiDiNiaoUseType
            this.douYinUseType = response.data.douYinUseType
            this.taoBaoUseType = response.data.taoBaoUseType
            this.pinDuoDuoUseType = response.data.pinDuoDuoUseType
            resolve('success')
          })
        } else {
          resolve('success')
        }
      })
      initFx.then((result) => {
        if (result === 'success') {
          this.init()
        }
      })
    },
    methods: {
      // 初始化
      init() {
        const printList = this.printList
        if (!printList || printList.length <= 0) {
          this.$message({ type: 'error', message: '打印列表不能为空！' })
          return
        }
        const orderId = printList[0].orderId
        this.printForm.enterpriseExpressId = ''
        this.printForm.expressOutletsId = ''
        this.loading = true
        getOrderInfo({ orderId: orderId }).then(response => {
          if (response.isError) return
          const orderDTO = response.data
          const orderType = orderDTO.orderType
          const externalPlatformType = orderDTO.externalPlatformType
          // 平台
          if (orderType === 33 || orderType === 34) {
            const platformTypeKeyList = this.platformTypeList.map(item => item.value)
            if (platformTypeKeyList.indexOf(externalPlatformType) !== -1) {
              this.platformDisabled = true
              this.printForm.platformType = externalPlatformType === 5 ? 3 : externalPlatformType
              this.changeAddress()
            }
          } else {
            this.printForm.platformType = 999
          }
          this.printerDisabled = true
          this.getListAllExpressOutlets()
        })
      },
      // 打印组件链接地址change
      changeAddress() {
        if (this.printForm.platformType !== 999) {
          if (this.printForm.platformType === 1) {
            this.printerAddress = '127.0.0.1:13888'
          } else if (this.printForm.platformType === 3) {
            this.printerAddress = '127.0.0.1:13528'
          } else if (this.printForm.platformType === 4) {
            this.printerAddress = '127.0.0.1:5000'
          }
          this.printerDisabled = false
          this.doConnect()
        }
      },
      // 获取快递公司及网点集合
      getListAllExpressOutlets() {
        this.loading = true
        const platformType = this.printForm.platformType
        const searchParams = {
          enterpriseId: this.getEnterpriseId(),
          platformType: platformType,
          supplierId: this.getSupplierId()
        }
        // 供应商端根据配置取数据
        if ((platformType === 999 && this.kuaiDiNiaoUseType === 1) || (platformType === 1 && this.douYinUseType === 1) ||
              (platformType === 3 && this.taoBaoUseType === 1) || (platformType === 4 && this.pinDuoDuoUseType === 1)) {
          searchParams.supplierId = ''
        }
        // 仓库端取设置的默认网点
        const warehouseFx = new Promise((resolve, reject) => {
          if (this.getWarehouseId()) {
            const params = {
              platformType: platformType,
              warehouseId: this.getWarehouseId(),
              source: 1
            }
            if ((platformType === 999 && this.kuaiDiNiaoUseType === 2) || (platformType === 1 && this.douYinUseType === 2) ||
                  (platformType === 3 && this.taoBaoUseType === 2) || (platformType === 4 && this.pinDuoDuoUseType === 2)) {
              params.source = 2
            }
            listWarehouseOutlets(params).then(response => {
              if (response.isError) {
                reject('获取仓库设置的默认网点错误！')
                return
              }
              resolve(response.data)
            })
          } else {
            resolve('')
          }
        })
        warehouseFx.catch((message) => {
          this.$message({
            type: 'error',
            message: message
          })
          return
        })
        warehouseFx.then((result) => {
          if (result) {
            searchParams.enterpriseExpressOutletsIds = result.map(item => item.enterpriseExpressOutletsId).join(',')
          }
          listAllExpressOutlets(searchParams).then(response => {
            this.loading = false
            if (response.isError) return
            this.expressList = response.data
          })
        })
      },
      // 平台切换事件
      platformTypeChange() {
        this.printForm.enterpriseExpressId = ''
        this.printForm.expressOutletsId = ''
        this.printForm.printerName = ''
        this.printersList = []
        this.printerDisabled = true
        this.printButton = false
        this.getListAllExpressOutlets()
        this.changeAddress()
      },
      // 快递公司选择事件
      expressChange() {
        const enterpriseExpressId = this.printForm.enterpriseExpressId
        if (this.expressList && enterpriseExpressId) {
          this.expressList.forEach(e => {
            if (e.enterpriseExpressId === enterpriseExpressId) {
              const outletsList = e.enterpriseExpressOutletsList
              const defaultList = outletsList.filter(o => {
                return o.defaultFlag === 1
              })
              this.printForm.expressOutletsId = ''
              if (defaultList && defaultList.length > 0) {
                this.printForm.expressOutletsId = defaultList[0].enterpriseExpressOutletsId
                this.printForm.enterpriseExpressId = defaultList[0].enterpriseExpressId
              } else {
                this.$message({
                  type: 'error',
                  message: '该快递下暂无默认网点,请先设置!'
                })
              }
              this.outletsList = defaultList
            }
          })
        }
      },
      // 链接打印机
      doConnect() {
        const that = this
        const platformType = that.printForm.platformType
        let socket = ''
        if (platformType === 1) {
          socket = that.douYinSocket
        } else if (platformType === 3) {
          socket = that.taoBaoSocket
        } else if (platformType === 4) {
          socket = that.pinDuoDuoSocket
        }
        if (socket && socket.readyState === 1) {
          // 获取打印机列表
          var request = {
            cmd: 'getPrinters',
            requestID: new Date().getTime().toString(),
            version: '1.0'
          }
          socket.send(JSON.stringify(request))
        } else {
          socket = new WebSocket('ws://' + this.printerAddress)
          if (platformType === 1) {
            that.douYinSocket = socket
          } else if (platformType === 3) {
            that.taoBaoSocket = socket
          } else if (platformType === 4) {
            that.pinDuoDuoSocket = socket
          }
        }
        that.loading = true
        // 打开Socket
        socket.onopen = function(event) {
          that.loading = false
          // alert('Websocket准备就绪,连接到客户端成功')
          that.printButton = false
          // 获取打印机列表
          var request = {
            cmd: 'getPrinters',
            requestID: new Date().getTime().toString(),
            version: '1.0'
          }
          socket.send(JSON.stringify(request))
        }
        // 监听消息
        socket.onmessage = function(event) {
          console.log('Client received a message', event)
          var data = JSON.parse(event.data)
          if (data.cmd === 'getPrinters') {
            const defaultPrinter = data.defaultPrinter
            that.defaultPrinter = defaultPrinter
            const printersList = data.printers
            printersList.forEach((p, index) => {
              if (p.name === defaultPrinter) {
                that.printForm.printerName = defaultPrinter
              }
            })
            that.printersList = printersList
            console.log(JSON.stringify(that.printersList))
          } else if (data.cmd === 'print') {
            // 打印任务提交是否成功
            if (data.status === 'success') {
              that.doClose()
            }
          } else if (data.cmd === 'notifyPrintResult') {
            // 打印结果
            if (data.taskStatus === 'printed' && data.printStatus[0].status === 'success') {
              // 更新打印状态
              that.updateProjectSendPrintStatus(data.printStatus[0].documentID)
            }
          } else {
            console.log('返回数据:' + JSON.stringify(data))
          }
        }
        // 监听Socket的关闭
        socket.onclose = function(event) {
          that.loading = false
          console.log('Client notified socket has closed', event)
        }
        socket.onerror = function(event) {
          that.$message({ type: 'error', message: '无法连接到打印机，请前往 物流设置-》电子面单 下载打印机组件！' })
          that.loading = false
          that.printButton = true
        }
        // 菜单跳转关闭连接
        that.$router.afterEach(function() {
          if (that.douYinSocket && that.douYinSocket.readyState === 1) {
            that.douYinSocket.close()
          }
          if (that.taoBaoSocket && that.taoBaoSocket.readyState === 1) {
            that.taoBaoSocket.close()
          }
          if (that.pinDuoDuoSocket && that.pinDuoDuoSocket.readyState === 1) {
            that.pinDuoDuoSocket.close()
          }
        })
      },
      // 更新打印状态
      updateProjectSendPrintStatus(waybillCode) {
        updateProjectSendPrintStatus(waybillCode).then(response => {
          if (response.isError) return
        })
      },
      // 关闭事件
      doClose() {
        this.$emit('callback', this.refreshFlag)
      },
      // 打印事件
      doPrint() {
        if (!this.printForm.enterpriseExpressId) {
          this.$message({
            type: 'error',
            message: '请选择快递公司'
          })
          return
        }
        if (!this.printForm.expressOutletsId) {
          this.$message({
            type: 'error',
            message: '请选择有默认网点的快递公司'
          })
          return
        }
        this.loading = true
        const printList = this.printList
        let countNum = 0
        printList.forEach(item => {
          const form = {
            sendId: item.sendId,
            enterpriseExpressId: this.printForm.enterpriseExpressId,
            platformType: this.printForm.platformType,
            expressOutletsId: this.printForm.expressOutletsId,
            enterpriseId: this.getEnterpriseId(),
            supplierId: this.getSupplierId(),
            warehouseId: this.getWarehouseId()
          }
          printProjectSend(form).then(response => {
            countNum += 1
            if (response.isError) return
            if (this.printForm.platformType === 999) {
              const eOrder = window.open('', 'eOrder', 'toolbar=no,scrollbars=yes,menubar=no')
              eOrder.document.write(response.data.printData)
              if (countNum === printList.length) {
                setTimeout(() => { eOrder.print() }, 100)
              }
            } else if (this.printForm.platformType === 1) {
              this.douYinPrint(response.data)
            } else if (this.printForm.platformType === 3) {
              this.taoBaoPrint(response.data)
            } else if (this.printForm.platformType === 4) {
              this.pinDuoDuoPrint(response.data)
            }
          })
        })
        this.loading = false
        this.doClose()
        this.refreshFlag = true
      },
      pinDuoDuoPrint(data) {
        const that = this
        const waybillCode = data.waybillCode
        const printData = data.printData
        const socket = that.pinDuoDuoSocket
        const contents = []
        if (printData) {
          contents.push(printData)
          const request = {
            cmd: 'print',
            requestID: new Date().getTime().toString(),
            version: '1.0',
            task: {
              taskID: new Date().getTime().toString(),
              printer: that.printForm.printerName,
              preview: false,
              documents: [{
                documentID: waybillCode,
                contents: contents
              }],
              notifyType: ['print']
            }
          }
          socket.send(JSON.stringify(request))
        }
      },
      taoBaoPrint(data) {
        const that = this
        const printData = data.printData
        const printCustomData = data.printCustomData
        const waybillCode = data.waybillCode
        const socket = that.taoBaoSocket
        const contents = []
        if (printData) {
          contents.push(printData)
          if (printCustomData) {
            contents.push(printCustomData)
          }
          const request = {
            cmd: 'print',
            requestID: new Date().getTime().toString(),
            version: '1.0',
            task: {
              taskID: new Date().getTime().toString(),
              printer: that.printForm.printerName,
              preview: false,
              documents: [{
                documentID: waybillCode,
                contents: contents
              }]
            }
          }
          console.log('数据:' + JSON.stringify(request))
          socket.send(JSON.stringify(request))
        }
      },
      douYinPrint(data) {
        const that = this
        const isEncrypt = data.isEncrypt
        const printData = data.printData
        const templateUrl = printData.templateUrl
        const socket = that.douYinSocket
        if (printData) {
          const contentsObj = { templateURL: templateUrl }
          const contents = []
          // 是否是加密
          if (isEncrypt === 'true') {
            contentsObj.params = printData.params
            contentsObj.signature = printData.sign
            contentsObj.encryptedData = printData.print_data
          } else {
            contentsObj.data = printData.print_data
          }
          contents.push(contentsObj)
          const request = {
            cmd: 'print',
            requestID: new Date().getTime().toString(),
            version: '1.0',
            task: {
              taskID: new Date().getTime().toString(),
              printer: that.printForm.printerName,
              preview: false,
              documents: [{
                documentID: printData.track_no,
                copy: 1,
                contents: contents
              }]
            }
          }
          socket.send(JSON.stringify(request))
        }
      }
    }
  }
</script>

<style lang="scss" scoped>
</style>
